/*
 * @Author: lll 1280388921@qq.com
 * @Date: 2025-05-08 20:31:51
 * @LastEditors: lll 1280388921@qq.com
 * @LastEditTime: 2025-05-08 20:57:26
 * @FilePath: /lesson39/mycond.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <pthread.h>
#include <unistd.h>

using namespace std;

int cnt = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void *Count(void *args)
{
    pthread_detach(pthread_self());
    uint64_t num = (uint64_t)args;
    cout<<"pthread "<<num<<" create success"<<endl;
    while (1)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond, &mutex);
        // 为什么在这里？？
        // 1.pthread_cond_wait让线程等待的时候，会自动释放锁！
        //
        cout << "pthread: " << num << " ,cnt= " << cnt++ << endl;
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
}

int main()
{
    for (uint64_t i = 0; i < 5; i++)
    {
        pthread_t tid;
        pthread_create(&tid, nullptr, Count, (void *)i);
        // 这里直接传值，不用取地址，否则主线程和新线程都指向同一个i
        // 传值直接拷贝，双方不会互相影响
        usleep(1000);
    }
    sleep(3);
    cout << "main thread ctrl begin!" << endl;
    while (1)
    {
        sleep(1);
        // pthread_cond_signal(&cond);
        pthread_cond_broadcast(&cond);
        //唤醒在cond的等待队列中的等待的一个线程，默认是第一个
        cout<<"signal one thread..."<<endl;
    }

    return 0;
}